<template>
  <div class="RotateRobot" ref="RotateRobot"></div>
</template>

<script>
import * as THREE from 'three'
import { FBXLoader } from 'three/examples/jsm/loaders/FBXLoader.js'

export default {
  name: `RotateRobot`,
  props: {
    width: {
      type: Number,
      default: 100
    },
    height: {
      type: Number,
      default: 100
    }
  },
  mounted () {
    this.init()
    this.animate()
  },
  methods: {
    init () {
      this.scene = new THREE.Scene()
      this.scene.background = null
      this.camera = new THREE.PerspectiveCamera(50, (window.innerWidth * this.width / 100) / (window.innerHeight * this.height / 100), 0.1, 2000)
      this.renderer = new THREE.WebGLRenderer({ alpha: true })
      this.renderer.setSize(window.innerWidth * this.width / 100, window.innerHeight * this.height / 100)
      this.$refs.RotateRobot.appendChild(this.renderer.domElement)

      // 面材质
      let buildMaterial = new THREE.MeshBasicMaterial({
        color: '#14557b', // 颜色
        transparent: true, // 是否开启使用透明度
        opacity: 0.20, // 透明度
        depthWrite: false, // 关闭深度写入 透视效果
        side: THREE.DoubleSide // 双面显示
      })

      // 线材质
      let lineMaterial = new THREE.LineBasicMaterial({
        color: '#2086b5',
        transparent: true,
        opacity: 0.3,
        depthWrite: false,
        side: THREE.DoubleSide
      })

      const loader = new FBXLoader()
      loader.load('robot.fbx', (object) => {
        this.fbxObject = object
        this.fbxObject.traverse(child => {
          if (child.isMesh) {
            child.material = buildMaterial
            child.frustumCulled = false
            child.castShadow = true

            child.material = buildMaterial // 赋模型材质
            if (child.geometry) {
              const edges = new THREE.EdgesGeometry(
                child.geometry
              )
              const line = new THREE.LineSegments(
                edges,
                lineMaterial // 赋线条材质
              )
              child.add(line)
            }
          }

          this.scene.add(object)
        })

        this.fbxObject.position.set(0, -55, 0)
        // this.fbxObject.position.set(0, -55, 0)
        this.fbxObject.rotation.set(0, 0, 0)
        this.fbxObject.scale.set(1.2, 1.2, 1.2)
        // this.fbxObject.scale.set(0.85, 0.85, 0.85)

        this.scene.add(object)
      })

      this.camera.position.set(0, 30, 140)
      this.camera.rotation.set(-0.18, 0, 0)
    },
    animate () {
      requestAnimationFrame(this.animate)
      if (this.fbxObject) {
        this.fbxObject.rotation.y += 0.01 // 旋转角度，根据需要调整
      }
      this.renderer.render(this.scene, this.camera)
    }
  }
}
</script>

<style scoped>
.RotateRobot{
  width: 100%;
  height: 100%;
}

</style>
